package utils;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.view.View;
import android.widget.RemoteViews;

import androidx.core.content.FileProvider;

import com.qb.devstore.MainActivity;
import com.qb.devstore.R;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.Date;
import java.util.List;

public class AppUtil {
    public static JSONArray getAppList(Context ctx) {
        List<ResolveInfo> ps;
        Intent intent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            ps = ctx.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_ALL);
        } else {
            ps = ctx.getPackageManager().queryIntentActivities(intent, 0);
        }
        JSONArray appList = new JSONArray();
        for(int i=0;i<ps.size();i++) {
            ResolveInfo pa = ps.get(i);
            String name = pa.loadLabel(ctx.getPackageManager()).toString();
            String packageName = pa.activityInfo.packageName;
            Drawable icon = pa.loadIcon(ctx.getPackageManager());
            icon.setBounds(0, 0, 96,96);
            try {
                PackageInfo pi = ctx.getPackageManager().getPackageInfo(packageName, 0);
                Integer versionCode = pi.versionCode;
                String versionName = pi.versionName;
                Long dtInstall = pi.firstInstallTime;
                Long dtUpdate = pi.lastUpdateTime;
                if ((pi.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) <= 0) {
                    JSONObject app = new JSONObject();
                    app.put("name",name);
                    app.put("packageName",packageName);
                    ImgUtil iu = new ImgUtil();
                    app.put("icon",iu.getImgStr(iu.drawable2Bitmap(icon)));
                    app.put("versionCode",versionCode);
                    app.put("versionName",versionName);
                    app.put("dtInstall",MyUtil.transferLongToDate("yyyy-MM-dd HH:mm:ss", dtInstall));
                    app.put("dtUpdate",MyUtil.transferLongToDate("yyyy-MM-dd HH:mm:ss", dtUpdate));
                    appList.put(app);
                } else {
                    //系统应用
                }
            } catch (PackageManager.NameNotFoundException | JSONException e) {
                e.printStackTrace();
            }
        }
        return appList;
    }
    public static String getAppStatus(Context ctx, String packageNameNet, int versionCodeNet) {
        String result = "";
        List<ResolveInfo> ps;
        Intent intent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            ps = ctx.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_ALL);
        } else {
            ps = ctx.getPackageManager().queryIntentActivities(intent, 0);
        }
        for(int i=0;i<ps.size();i++) {
            ResolveInfo pa = ps.get(i);
            String packageName = pa.activityInfo.packageName;
            if (packageNameNet.equals(packageName)) {
                try {
                    PackageInfo pi = ctx.getPackageManager().getPackageInfo(packageName, 0);
                    Integer versionCode = pi.versionCode;
                    if (versionCodeNet <= versionCode) {
                        result = "installed";
                    } else {
                        result = "update";
                    }
                } catch (PackageManager.NameNotFoundException e) {
                    result = "installed";
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    // 下载apk（显示通知）
    public static int downloadNum = 0;
    public static void dloadApk(Context ctx,String urlStr,String apkName,Boolean silence) {
        Integer nId = Integer.valueOf(String.valueOf(new Date().getTime()).substring(0, 10));
        MiniLoadingDialog mMiniLoadingDialog;
        mMiniLoadingDialog = WidgetUtils.getMiniLoadingDialog(ctx);
        mMiniLoadingDialog.setDialogSize(150,150);
        String destFileDir = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "Download/";
        if(MyUtil.isFolderExists(destFileDir)) {
            showLoading(mMiniLoadingDialog,true);
            String apkPath = destFileDir+apkName;
            MyUtil.showLog("dloadApk","开始下载");
            DownloadUtil dlu = new DownloadUtil(urlStr);
            if (downloadNum<5) downloadNum++;
            dlu.download(destFileDir, apkName, new DownloadUtil.OnDownloadListener() {
                @Override
                public void onDownloadSuccess(File file) {
                    MyUtil.showLog("dloadApk","下载完成");
                    if (downloadNum>0) downloadNum--;
                    //下载完成进行相关逻辑操作
                    if (silence) {
                        // 静默安装
                    } else {
                        Boolean installSuccess = installApk(ctx,apkPath);
                        if (installSuccess) {
                            MyUtil.showLog("dloadApk","installSuccess");
                        }
                    }
                }

                @Override
                public void onDownloading(int progress) {
                    showLoading(mMiniLoadingDialog,false);
                    //下载进行中展示进度
                    if (progress % 10 == 0 && progress > 0) {
                        MyUtil.showLog("dloadApk","下载进度:"+progress);
                    }
                    if (silence) {
                        // 系统更新不显示进度
                    } else {
                        setNotification(ctx,nId,progress,apkName,dlu);
                    }
                }

                @Override
                public void onDownloadFailed(Exception e) {
                    showLoading(mMiniLoadingDialog,false);
                    if (downloadNum>0) downloadNum--;
                    //下载异常进行相关提示操作
                    MyUtil.showLog("dloadApk",apkName+"下载失败"+e);
                    MyUtil.showCookieBar(ctx,apkName+"下载失败",e.getMessage(),"download");
                    setNotification(ctx,nId,-1,apkName,dlu);
                }
            });
        } else {
            MyUtil.showLog("dloadApk",apkName+"下载失败"+"目录不存在");
            MyUtil.showCookieBar(ctx,apkName+"下载失败","目录不存在","download");
        }
    }
    // 安装apk
    public static boolean installApk(Context ctx,String apkPath) {
        File apkfile = new File(apkPath);
        if (!apkfile.exists()) {
            return false;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Intent install = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + ctx.getPackageName()));
        install.setAction(Intent.ACTION_VIEW);
        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        install.addCategory(Intent.CATEGORY_DEFAULT);
        //判断是否是AndroidN以及更高的版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            try {
                String file_provider = "com.qb.devstore.fileprovider";
                Uri contentUri = FileProvider.getUriForFile(ctx.getApplicationContext(), file_provider, apkfile);
                intent.setAction(Intent.ACTION_VIEW);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            intent.setDataAndType(Uri.fromFile(apkfile), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        try {
            ctx.startActivity(intent);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    // loading
    private static void showLoading(MiniLoadingDialog dialog, Boolean loading) {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                if (loading) dialog.show();
                else dialog.dismiss();
            }
        });
    }

    private static void setNotification(Context ctx, int nId, int progress, String apkName, DownloadUtil dlu) {
        if (ctx==null){
            return;
        }
        String dLoadPercent = progress<0?"下载失败":"已下载："+progress+"%";
        //MyUtil.showLog("setNotification",nId+",进度:"+dLoadPercent);
        RemoteViews remoteViews = new RemoteViews(ctx.getPackageName(), R.layout.notifaction_download);
        remoteViews.setTextViewText(R.id.tv_dload_name, apkName);
        remoteViews.setTextViewText(R.id.tv_dload_percent, dLoadPercent);
        if (progress == -1) {
            remoteViews.setTextColor(R.id.tv_dload_percent,ctx.getResources().getColor(R.color.red_start));
        } else {
            remoteViews.setTextColor(R.id.tv_dload_percent,ctx.getResources().getColor(R.color.primary_normal));
            remoteViews.setProgressBar(R.id.pb_dload, 100, progress, false);
        }
        NotificationUtil nu = new NotificationUtil(ctx);
        NotificationManager manager = nu.getManager();
        //点击按钮取消下载
        Intent itDLoadCancel = new Intent(ctx, MainActivity.class);
        Bundle mBundle = new Bundle();
        //MyUtil.showLog("dlu",dlu);
        mBundle.putParcelable("DOWNLOAD_UTIL", dlu);
        //mBundle.putParcelable("NOTIFICATION_UTIL", nu);
        itDLoadCancel.putExtras(mBundle);
        itDLoadCancel.putExtra("NOTIFICATION_ID",nId);
        PendingIntent piDLoadCancel = PendingIntent.getActivity(ctx, 0,itDLoadCancel, 0);
        remoteViews.setOnClickPendingIntent(R.id.btn_dload_cancel,piDLoadCancel);
        remoteViews.setViewVisibility(R.id.btn_dload_cancel,View.GONE);
        Notification notification = nu.setContentIntent(null)
                .setContent(remoteViews)
                .setFlags(Notification.FLAG_AUTO_CANCEL)
                .setOnlyAlertOnce(true)
                .getNotification("下载", apkName, R.drawable.download);
        manager.notify(nId, notification);
    }
}
